﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using WHC.Security.BLL;
using WHC.Security.Entity;
using WHC.OrderWater.Commons;
using WHC.Security.Common;

namespace WHC.Security.UI
{
    public partial class FrmFunction : BaseForm
    {
        private Function function = new Function();
        private string currentID = string.Empty;

        public FrmFunction()
        {
            InitializeComponent();
        }

        private void FrmFunction_Load(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void RefreshTreeView()
        {
            treeView1.Nodes.Clear();
            treeView1.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            //绑定下拉列表
            List<FunctionInfo> comboList = function.GetAll();
            comboList = CollectionHelper<FunctionInfo>.Fill(-1, 0, comboList, "PID", "ID", "Name");
            this.cmbUpperFunction.Items.Clear();  
            this.cmbUpperFunction.Items.Add(new CListItem("无","-1"));

            //绑定树控件
            List<FunctionInfo> list = function.GetAll();
            foreach (FunctionInfo info in comboList)
            {
                this.cmbUpperFunction.Items.Add(new CListItem(info.Name, info.ID.ToString()));
            }

            foreach (FunctionInfo info in list)
            {
                if (info.PID != -1)
                {
                    continue;
                }

                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name;
                item.Tag = info.Name;
                this.treeView1.Nodes.Add(item);

                AddChildNode(list, item);
            }

            Cursor.Current = Cursors.Default;
            treeView1.EndUpdate();
            this.treeView1.ExpandAll();
        }

        private void ClearInput()
        {
           // this.txtFunctionID.Text = "";
            this.txtName.Text = "";
            this.cmbUpperFunction.SelectedIndex = 0;
            this.lvwRole.Items.Clear();
        }

        private void RefreshRoles(int id)
        {
            this.lvwRole.Items.Clear();
            Role role = new Role();
            foreach (RoleInfo info in role.GetRolesByFunction(id))
            {
                CListItem item = new CListItem(info.Name, info.ID.ToString());
                this.lvwRole.Items.Add(item);
            }
            if (this.lvwRole.Items.Count > 0)
            {
                this.lvwRole.SelectedIndex = 0;
            }
        }

        private void AddChildNode(List<FunctionInfo> list, TreeNode fnode)
        {
            foreach (FunctionInfo info in list)
            {
                if (info.PID != int.Parse(fnode.Name))
                {
                    continue;
                }
                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name;
                item.Tag = info.Name;
                fnode.Nodes.Add(item);

                AddChildNode(list, item);
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeNode node = treeView1.GetNodeAt(e.X, e.Y);
                if (node != null)
                {
                    treeView1.SelectedNode = node;
                }
            }

            base.OnMouseDown(e);
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && !string.IsNullOrEmpty(node.Name))
            {
                if (MessageUtil.ShowYesNoAndTips("您确认删除吗?") == DialogResult.Yes)
                {
                    //int id = Convert.ToInt32(node.Name);
                    try
                    {
                        function.Delete(node.Name);
                        RefreshTreeView();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    }
                }
            }
        }

        private void menu_Add_Click(object sender, EventArgs e)
        {
            ClearInput();
            currentID = "";
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && node.Tag != null)
            {
                for (int i = 0; i < this.cmbUpperFunction.Items.Count; i++)
                {
                    CListItem item = this.cmbUpperFunction.Items[i] as CListItem;
                    if (item != null && item.Value == node.Name)
                    {
                        this.cmbUpperFunction.SelectedIndex = i;
                    }
                }
            }
            this.txtName.Focus();
        }

        private void menu_Update_Click(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void menu_ExpandAll_Click(object sender, EventArgs e)
        {
            this.treeView1.ExpandAll();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                int id = Convert.ToInt32(e.Node.Name);
                FunctionInfo info = (FunctionInfo)function.FindByID(id.ToString());

                if (info != null)
                {
                    currentID = id.ToString();

                    this.txtName.Text = info.Name;
                   // this.txtFunctionID.Text = info.ControlID;

                    FunctionInfo info2 = (FunctionInfo)function.FindByID(info.PID.ToString());
                    if (info2 != null)
                    {
                        for (int i = 0; i < this.cmbUpperFunction.Items.Count; i++)
                        {
                            CListItem item = this.cmbUpperFunction.Items[i] as CListItem;
                            if (item != null && item.Value == info2.ID.ToString())
                            {
                                this.cmbUpperFunction.SelectedIndex = i;
                            }
                        }
                    }
                    else
                    {
                        int index = this.cmbUpperFunction.FindString("无");
                        this.cmbUpperFunction.SelectedIndex = index;
                        //this.txtSystemType.Text = info.SystemType_ID;
                    }

                    RefreshRoles(id);
                }
            }
        }

        private FunctionInfo SetFunction(FunctionInfo info)
        {
            info.Name = this.txtName.Text;
            CListItem item = this.cmbUpperFunction.SelectedItem as CListItem;
            info.PID = Convert.ToInt32(item.Value);
            //info.ControlID = this.txtFunctionID.Text;
            info.ControlID = info.PID.ToString();
            return info;
        }

        private void SetSystemTypeVisible(bool visible)
        {
            //this.txtSystemType.Visible = visible;
            //this.lblSystemType.Visible = visible;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            CListItem item = this.cmbUpperFunction.SelectedItem as CListItem;
            if (item == null)
                return;

            #region 验证用户输入
            if (this.txtName.Text == "")
            {
                MessageUtil.ShowTips("功能名称不能为空");
                this.txtName.Focus();
                return;
            }
            //else if (this.txtFunctionID.Text == "")
            //{
            //    MessageUtil.ShowTips("功能ID不能为空");
            //    this.txtFunctionID.Focus();
            //    return;
            //}
            //else if (this.txtSystemType.Visible && this.txtSystemType.Text.Length == 0)
            //{
            //    MessageUtil.ShowTips("系统类型编号不能为空");
            //    this.txtSystemType.Focus();
            //    return;
            //}

            #endregion

            if (!string.IsNullOrEmpty(currentID))
            {
                int id = Convert.ToInt32(currentID);
                try
                {
                    FunctionInfo info = function.FindByID(id.ToString());
                    if (info != null)
                    {
                        info = SetFunction(info);
                        function.Update(info, info.ID.ToString());

                        RefreshTreeView();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
            else
            {

                string pid = item.Value;
                FunctionInfo functionInfo = function.FindByID(pid) as FunctionInfo;

                if (functionInfo != null)
                {
                    //string filter = string.Format("ControlID='{0}' and SystemType_ID='{1}'", this.txtFunctionID.Text, functionInfo.SystemType_ID);
                    //bool isExist = function.IsExistRecord(filter);
                    //if (isExist)
                    //{
                    //    MessageUtil.ShowTips("指定功能控制ID重复，请重新输入！");
                    //    this.txtName.Focus();
                    //    return;
                    //}
                }
                else
                {
                    //当新建系统类型的时候
                    functionInfo = new FunctionInfo();
                    functionInfo.PID = -1;
                    functionInfo.SystemType_ID = "WareMis";
                    //functionInfo.ControlID = this.txtFunctionID.Text;

                    //string filter = string.Format("ControlID='{0}' and SystemType_ID='{1}'", this.txtFunctionID.Text, functionInfo.SystemType_ID);
                    //bool isExist = function.IsExistRecord(filter);
                    //if (isExist)
                    //{
                    //    MessageUtil.ShowTips("指定功能控制ID重复，请重新输入！");
                    //    this.txtName.Focus();
                    //    return;
                    //}
                }

                FunctionInfo info = new FunctionInfo();
                info = SetFunction(info);
                info.SystemType_ID = functionInfo.SystemType_ID;//和父节点的SystemType_ID一样。

                try
                {
                    function.Insert(info);
                    RefreshTreeView();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            menu_Add_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            menu_Delete_Click(null, null);
        }

        private void cmbUpperFunction_SelectedIndexChanged(object sender, EventArgs e)
        {
            CListItem item = this.cmbUpperFunction.SelectedItem as CListItem;
            if (item != null && item.Value == "-1")
            {
                SetSystemTypeVisible(true);
            }
            else
            {
                SetSystemTypeVisible(false);
            }
        }
    }
}
